package sample.main;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.google.common.io.Files;
import de.felixroske.jfxsupport.FXMLController;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import sample.constants.FilesIndexConstants;
import sample.utils.CacheStudent;
import sample.utils.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.ResourceBundle;

/**
 * @author taowenchen
 */
@FXMLController
public class MainPageController implements Initializable {

    @FXML
    GridPane gridPane;


    @FXML
    public void addClass(ActionEvent event) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择Excel文件");
        Stage selectFile = new Stage();
        fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
        fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("All Excel", "*.xls"),
                new FileChooser.ExtensionFilter("XLS", "*.xls"), new FileChooser.ExtensionFilter("XLSX", "*.xlsx"));
        File file = fileChooser.showOpenDialog(selectFile);
        if (file != null) {
            List<Student> studentList = new ArrayList<>();
            EasyExcel.read(file, Student.class, new AnalysisEventListener<Student>() {
                @Override
                public void invoke(Student o, AnalysisContext analysisContext) {
                    studentList.add(o);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    saveStudent(studentList);
                }

                private void saveStudent(List<Student> studentList) {
                    try {
                        final File studentFile = new File(FileUtils.getFile() + String.format(FilesIndexConstants.STUDENT_FILE_DIR, file.getName() + ".dat"));
                        if (!studentFile.getParentFile().exists()) {
                            studentFile.getParentFile().mkdirs();
                        }
                        if (!studentFile.exists()) {
                            studentFile.createNewFile();
                        }
                        Files.write(JSON.toJSONString(studentList).getBytes(StandardCharsets.UTF_8), studentFile);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }).sheet(0).doRead();
        }
    }


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        final File studentDir = new File(FileUtils.getFile() + FilesIndexConstants.STUDENT_FILE_DIR_P);
        final File[] files = studentDir.listFiles();
        for (int i = 0; i < Objects.requireNonNull(files).length; i++) {
            try {
                File file = files[i];
                final List<String> strings = Files.readLines(file, StandardCharsets.UTF_8);
                final List<Student> students = JSON.parseArray(strings.get(0), Student.class);
                CacheStudent.cacheStudent.put(file.getName(), students);
                gridPane.add(addNewClassPane(file.getName(), students.size()), i % 5, i / 5);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private Pane addNewClassPane(String name, int length) {
        Pane pane = new Pane();
        pane.setStyle("-fx-border-color: #b0bdc4;-fx-border-radius: 10px;-fx-border-insets: 5");
        final Label label = new Label("班级名称：" + name.substring(0,name.indexOf(".")));
        label.setLayoutY(10);
        label.setLayoutX(25);
        final Label label2 = new Label("班级人数：" + length);
        label2.setLayoutY(35);
        label2.setLayoutX(25);

        Button button = new Button("学生");
        button.setLayoutX(25);
        button.setLayoutY(60);
        button.setOnAction(event -> {

        });
        Button button2 = new Button("成绩");
        button2.setLayoutX(100);
        button2.setLayoutY(60);
        pane.getChildren().addAll(label, label2, button, button2);
        return pane;
    }


}
